package study.chapter03.thread.producerandcomsumer;

public class TestProducerAndConsumer {
    public static void main(String[] args) {
        SyncBuffer buffer = new SyncBuffer();

        new Thread(new Producer(buffer)).start();
        new Thread(new Consumer(buffer)).start();
    }

}

//生产者
class Producer implements Runnable{
    SyncBuffer buffer;

    public Producer(SyncBuffer buffer) {
        this.buffer = buffer;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {
            buffer.push(new Chicken(i));
            System.out.println("生产了第" + i + "只鸡");
        }
    }
}

//消费者
class Consumer implements Runnable{
    SyncBuffer buffer;

    public Consumer(SyncBuffer buffer) {
        this.buffer = buffer;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {
            System.out.println("消费了-------->第" + (buffer.pop().id) + "只鸡");
        }
    }
}

//产品
class Chicken {
    int id;

    public Chicken(int id) {
        this.id = id;
    }
}

//缓冲区
class SyncBuffer{
    Chicken[] chickens = new Chicken[10];
    //容器计数器
    int count = 0;

    //生产者生产产品
    public synchronized void push(Chicken chicken){
        //如果容器满了，等待消费者来消费
        if (count == chickens.length){
            //通知消费者来消费
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else {
            //如果没满，就放入产品
            chickens[count] = chicken;
            count++;

            //通知消费者来消费
            this.notifyAll();
        }

    }



    //消费者消费产品
    public synchronized Chicken pop(){
        if (count == 0){
            //等待生产者生产
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        //可以消费
        count--;
        Chicken chicken = chickens[count];

        //吃完了通知生产者生产
        this.notifyAll();

        return chicken;

    }

}
